package io.gitee.mingbaobaba.security.core.convert;

import io.gitee.mingbaobaba.security.core.constants.SecurityConstant;
import io.gitee.mingbaobaba.security.core.domain.SecurityLoginParams;
import io.gitee.mingbaobaba.security.core.domain.SecurityToken;
import io.gitee.mingbaobaba.security.core.factory.SecurityFactory;
import io.gitee.mingbaobaba.security.core.utils.CommonUtil;
import io.gitee.mingbaobaba.security.core.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Objects;

/**
 * <p>>SecurityLoginModel->SecurityToken</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/18 9:59
 */
public class SecurityLoginParamsConvertToken implements Convert<SecurityLoginParams, SecurityToken> {

    private final String loginId;

    public SecurityLoginParamsConvertToken(String loginId) {
        this.loginId = loginId;
    }

    @Override
    public SecurityToken convert(SecurityLoginParams source) {
        SecurityToken securityToken = SecurityToken.builder()
                .token(StringUtils.defaultIfBlank(source.getToken(), CommonUtil.generateToken.get()))
                .loginId(loginId)
                .deviceType(StringUtils.defaultString(source.getDeviceType(), SecurityConstant.UNKNOWN))
                .timeout(Objects.isNull(source.getTimeout()) ? SecurityFactory.getConfig.get()
                        .getTimeout() : source.getTimeout())
                .activityTime(DateUtil.formatDateTime.apply(new Date()))
                .activityTimeout(Objects.isNull(source.getActivityTimeout()) ?
                        SecurityFactory.getConfig.get().getActivityTimeout() : source.getActivityTimeout())
                .state(SecurityConstant.TOKEN_STATE_NORMAL)
                .createTime(DateUtil.formatDateTime.apply(new Date()))
                .build();
        //设置token挂载数据
        securityToken.getTokenMountData().putAll(source.getTokenMountData());
        return securityToken;
    }
}
